<?php

	// +----------------------------------------------------------------------
	// | 用户经验管理
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\ucenter;

	use app\model\ucenter\User as UserModel;
	use app\model\ucenter\UserGrade as UserGradeModel;
	use app\common\event\Base;
	use think\Exception;

	class UserExperience extends Base
	{

		/**
		 * 登录赠送经验
		 * @param        $user
		 * @param        $rule
		 * @param null $log
		 * @param string $channel
		 * @throws Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/4/3 12:45
		 */
		public static function login($user, $rule, $log = null, $channel = 'wap')
		{
			$point = [];
			$point['change_code'] = 'login';
			$point['relation_id'] = $log['id'];
			$point['point'] = $rule;
			self::change($point, $user);
		}

		/**
		 * 经验变更，一般用于其他途径调用
		 * @param array $param
		 * @param UserModel $user
		 * @param UserModel $admin
		 * @return mixed
		 * @throws Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public static function change($param, $user, $admin = null)
		{
			$log = [];
			$log['change_code'] = $param['change_code'];
			$user['experience'] = $user['experience'] + $param['experience'];
			$log['experience'] = $param['experience'];
			$log['relation_id'] = $param['relation_id'];
			isset($admin) && $log['admin_id'] = $admin['id'];
			switch ($param['change_code']) {
				case 'user_sign':
					// 签到
					$log['message'] = '每日签到增加经验';
					break;
				case 'add_question':
					$log['message'] = '帖子增加经验';
					break;
				case 'sign':
					// 兑换礼品
					$log['message'] = '每日签到增加经验';
					break;
				case 'login':
					// 登录赠送
					$log['message'] = '登录赠送增加经验';
					break;
				case 'online':
					// 发布问题
					$log['message'] = '每日在线学习30分钟送经验';
					break;
				default:

					isset($param['message']) && $log['message'] = $param['message'];
					isset($param['remark']) && $log['remark'] = $param['remark'];
					break;
			}
			// 等级判断

			if ($user->grade['capping_experience'] <= $user['experience']) {
				$grade = UserGradeModel::where('status', 1)->where('capping_experience', '>=', $user['capping_experience'])->order('capping_experience ASC')->find();
				if ($grade) {
					$user['grade_id'] = $grade['id'];
				}
			}
			if (!$user->save()) {
				throw new Exception('用户信息保存失败');
			}
			// 增加经验变动日志
			if (!$user->experiences()->save($log)) {
				throw new Exception('用户经验变更信息保存失败');
			}


			return $user;
		}

	}
